import React, { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom';
// 导入接口
import { getDetail, addCar } from '@/api/detail';
// 导入轮播图组件
import Myswiper from '@/components/Myswiper'

// 导入数据类型
import { detailObjType } from '@/types/home'
import { Button, Toast } from 'antd-mobile'

// 导入头部导航组件
import Navheader from '@/components/Navheader';

import { useSelector } from 'react-redux'

export default function Detail() {
    const [detailObj, setDetailObj] = useState<detailObjType | {}>({});
    const [swiperArr, setSwiperArr] = useState([])
    const loc = useLocation();
    const userid = useSelector((state: { userid: string, counter: { userid: string } }) => state.counter.userid)

    // 获取页面传递的参数
    // console.log(loc);
    const proid = loc.search.split('=')[1]
    useEffect(() => {

        // console.log(proid);
        // 请求详情页数据
        getDetail({ proid: proid }).then(res => {
            console.log('res', res);
            setDetailObj(res.data.data)
            setSwiperArr(res.data.data.banners[0].split(',').map((item: string) => ({ img: item })))
            // 方式1: 将该数组改造成 符合轮播图参数类型的结构
            // [{img:url},{img:url}]
        })

    }, [])

    const formatMoneyFn = (money: number) => {
        console.log(money);

        return <span style={{ color: 'red' }}>${money.toFixed(2)} 元</span>
    }
    return (
        <div className='detail'>
            {/* 头部导航组件 */}
            <Navheader title={'详情'} isshow={true}></Navheader>
            {/* 轮播图 */}
            {
                swiperArr.length > 0 && <Myswiper swiperArr={swiperArr}></Myswiper>
            }
            {/* 详情页的数据 */}
            <div>
                <p>{
                    (detailObj as detailObjType).originprice &&
                    formatMoneyFn((detailObj as detailObjType).originprice)
                }</p>
            </div>

            {/*底部加入购物车的菜单*/}
            <div>
                <Button block shape='rounded' color='primary' onClick={() => {
                    // 加入购物车接口
                    addCar({ proid: proid, userid: userid, num: '1' }).then(res => {
                        console.log(res);
                        if (res.data.code == 200) {
                            Toast.show({
                                content: "加入购物车",
                                duration: 1000
                            })
                        }

                    })

                }}>加入购物车</Button>
                <Button block shape='rounded' color='primary'>立即结算</Button>
            </div>
        </div>
    )
}